package anatex.translate;

import java.util.Date;
import java.util.List;
import java.util.ListIterator;

import javax.persistence.CascadeType;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.TypedQuery;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.roo.addon.entity.RooEntity;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.tostring.RooToString;
import anatex.domain.CustomLocale;
import anatex.domain.Document;
import anatex.domain.KeywordDocument;
import anatex.domain.Task.EnumState;
import anatex.domain.Keyword;


@RooJavaBean
@RooToString
@RooEntity(finders = { "findTranslateTasksByCurrentStateAndEnabled" })
public class TranslateTask {

    @ManyToOne
    private Document document;

    @ManyToOne
    private CustomLocale locale;

    private Boolean enabled;
    
    private Integer length;

    public enum EnumState {

        NOT_STARTED, WORKING, FINISHED
    }

    ;

    private EnumState currentState;

    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(style = "SS")
    private Date translationTime;

    public void setCurrentState(EnumState currentState) {
        this.currentState = currentState;
    }
    
    public void setDocument(Document document) {
        this.document = document;
        calculateLength();
    }
    
    public void calculateLength(){
    	List<KeywordDocument> words = KeywordDocument.findKeywordDocumentsByDocument(document).getResultList();
    	if(words.size()<1){
    		this.length = -1;
    		return;
    	}
    	ListIterator<KeywordDocument> li = words.listIterator();
    	Integer currentLength = 0;
    	while(li.hasNext()){
    		currentLength += li.next().getKeyword().getText().length();
    	}
    	currentLength +=words.size()-1;
    	this.length = currentLength;
    }
}
